package com.exercise.ThreadSynchronization.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();

    //共享资源
    private int sharedData = 0;

    //读操作
    public int read(){
        readLock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+" reading: "+sharedData);
            return sharedData;
        }finally {
            readLock.unlock();
        }
    }

    //写操作
    public void write(int newValue){
        writeLock.lock();
        try{
            System.out.println(Thread.currentThread().getName()+" writing: "+newValue);
            sharedData = newValue;
        }finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadWriteLockExample example = new ReadWriteLockExample();

        //多个读线程
        Runnable readTask = () ->{
            for (int i = 0; i < 5; i++) {
                example.read();
                try{
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        };

       // 一个写线程
        Runnable writeTask = () ->{
            for (int i = 0; i < 3; i++) {
                example.write(i);
                try{
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        };

        Thread[] readers = new Thread[3];
        for (int i = 0; i < readers.length; i++) {
            readers[i] = new Thread(readTask, "Reader-" + i);
            readers[i].start();
        }
        Thread writer = new Thread(writeTask, "Writer");
        writer.start();

        //等待所有线程完成
        for (int i = 0; i < 3; i++) {
            readers[i].join();
        }
        writer.join();

        System.out.println("所有线程执行完毕");
    }
}
